package com.coship.vas.dapg.util;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.dbcp.BasicDataSource;

/**
 * 数据库工具类
 * 
 * @作者 905613 陈开源 深圳市同洲电子股份有限公司(增值运营产品线)
 * 
 */
public class DataBaseUtil {

	/**
	 * 查询
	 * 
	 * @param query
	 * @return
	 */
	public static List<HashMap<String, String>> searchBySQLScript(String query) {
		Connection conn = getConnection();
		List<HashMap<String, String>> results = new ArrayList<HashMap<String, String>>();

		try {
			Statement stmt = conn.createStatement();
			ResultSet rest = stmt.executeQuery(query);

			while (rest.next()) {
				HashMap<String, String> record = getHashMapRecord(rest);
				results.add(record);
			}
			rest.close();
			stmt.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return results;
	}

	/**
	 * 转换resultset为HashMap
	 * 
	 * @param rs
	 * @return
	 */
	protected static HashMap<String, String> getHashMapRecord(ResultSet rs) {
		ResultSetMetaData rsMeta;
		try {
			rsMeta = rs.getMetaData();
			int i = rsMeta.getColumnCount();
			HashMap<String, String> hm = new HashMap<String, String>();
			String sColumName = null;
			String value = "";
			for (; i > 0; i--) {
				sColumName = rsMeta.getColumnName(i).toLowerCase();
				try {
					if (rs.getObject(sColumName) != null)
						value = rs.getObject(sColumName).toString();
				} catch (Exception e) {
				}
				hm.put(sColumName, value);
			}
			return hm;
		} catch (SQLException e) {

		}
		return null;
	}

	/**
	 * 获取数据库连接
	 * 
	 * @return
	 */
	private static Connection getConnection() {
		BasicDataSource bds = (BasicDataSource) SpringBeanFactoryUtil
				.getBean("datasource");
		try {
			Connection conn = bds.getConnection();
			return conn;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

}
